var express = require('express')
var path = require('path')
var session = require('express-session')
var cookieParser = require('cookie-parser')
var mongoose = require('mongoose')
var mongoStore = require('connect-mongo')(session) // mongodb登录会话持久化
var bodyParser = require('body-parser')
var morgan = require('morgan')
var serveStatic = require('serve-static')
// var multipart = require('connect-multiparty')()
var fs = require('fs') // 引入文件读写模块
var port = process.env.PORT || 3000
var app = express()
// mongoose.connect('mongodb://localhost/imoocNode')
mongoose.Promise = global.Promise
var dbUrl = 'mongodb://localhost/imoocNode'
mongoose.connect(dbUrl,{useMongoClient:true})


// models loading
var models_path = __dirname + '/app/models'
var walk = function (path) {
    fs
        .readdirSync(path)
        .forEach(function (file) {
            var newPath = path + '/' + file
            var stat = fs.statSync(newPath)
            if (stat.isFile()) {
                // 如果是 js 或者 coffee 文件
                if (/(.*)\.(js|coffee)/.test(file)) {
                    require(newPath)
                }
            } else if (stat.isDirectory()) {
                walk(newPath)
            }
        })
}
walk(models_path)
// 这样再其他地方可以通过 User = mongoose.model('User') 拿到模型


// var db = mongoose.connection;
// db.on('error', console.error.bind(console, 'connection error..'));
// db.once('open', function callback(){
//     console.log('multivision db opened');
// });
app.set('views', './app/views/pages')
app.set('view engine', 'jade')
// 表单提交 multipart 处理表单提交的数据multipart/form-data
// app.use(multipart)
// 提交表单时，将数据格式化
app.use(bodyParser())
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())

// session 和 cookieParser
// app.use(express.cookieParser())
app.use(cookieParser())
app.use(session({
    secret: 'imooc',
    resave: false,
    saveUninitialized: true,
    store: new mongoStore({
        url: dbUrl,
        collection: 'sessions'
    })
}))

var env = process.env.NODE_ENV || 'development'
if('development' === env) {
    app.set('showStackError', true) // 设置错误
    app.use(morgan(':method :url :status'))
    app.locals.pretty = true // 格式化后的代码，可读性好
    mongoose.set('debug', true)
}
// if('development' === app.get('env')) {
//     app.set('showStackError', true) // 设置错误
//     app.use(morgan(':method :url :status'))
//     app.locals.pretty = true // 格式化后的代码，可读性好
//     mongoose.set('debug', true)
// }

require('./config/routes')(app)
// 样式路径或脚本再 bower_components中查找
app.listen(port)
app.use(serveStatic(path.join(__dirname, 'public')))
app.locals.moment = require('moment')

console.log('imooc started on' + port)